/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servant;

import common.Envelope;
import common.Framer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mateusz
 */
public class TaskReceiver implements Runnable {

    private ServerSocket serverSocket;
    private Socket socket;
    private OutputStream out;
    private InputStream in;
    private Framer framer;
    private File path;

    public TaskReceiver(int port, File path){
        this.path = path;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException ex) {
            Logger.getLogger(TaskReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public TaskReceiver(ServerSocket serverSocket, Socket socket, OutputStream out, InputStream in, Framer framer) {
        this.serverSocket = serverSocket;
        this.socket = socket;
        this.out = out;
        this.in = in;
        this.framer = framer;
    }

    public void listen() {
        while(true){
            try {
                socket = serverSocket.accept();
                TaskReceiver tr = new TaskReceiver(serverSocket, socket, socket.getOutputStream(), socket.getInputStream(), new Framer(socket));
                new Thread(tr).start();
            } catch (IOException ex) {
                Logger.getLogger(TaskReceiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void run(){
        ReceiverProtocol protocol = new ReceiverProtocol(socket, framer, path);
        while(!protocol.isEnded()){
            Envelope env = framer.get();
            protocol.process(env);
        }
    }
}
